

<template>
    <div style="padding: 10px; margin-bottom: 50px">

      <el-affix>
        <MainHeader/>
      </el-affix>
      <el-row style="margin-top: 30px;margin-left: 15%">
        <el-col :span="6">
          <el-card>
            <div style="display: flex; gap: 5px">
              <el-input v-model="keyword" placeholder="搜索联系人" ></el-input>
              <el-button @click="searchUser" >搜索</el-button>
            </div>
          </el-card>
          <el-card style="width: 100%; height: 227px; color: #333;overflow: auto">
            <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc;text-align: left">搜索结果</div>
            <div style="padding: 10px 0" v-for="user in searchUsers" :key="user.username">
              <span @click="change(user,0)">{{ user.username }}</span>
              <i class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 16px; cursor: pointer"
                 @click="change(user.id,user.username)"></i>
              <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user.username === chatUser.username">chatting...</span>
            </div>
          </el-card>

          <el-card style="width: 100%; min-height: 300px; color: #333">
            <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc;text-align: left">最近联系<span style="font-size: 12px">（发送私信）</span></div>
            <div style="padding: 10px 0" v-for="user in users" :key="user.username">
              <span @click="change(user,1)">{{ user.username }}</span>
              <i class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 16px; cursor: pointer"
                 @click="change(user.id,user.username)"></i>
              <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user.username === chatUser.username">chatting...</span>
            </div>
          </el-card>

        </el-col>
        <el-col :span="8">
          <div style="width: 800px; margin: 0 auto; background-color: white;
                      border-radius: 5px; box-shadow: 0 0 10px #ccc">
            <div style="text-align: center; line-height: 50px;">
              （{{ chatUser.username }}）
            </div>
            <div style="height: 350px; overflow:auto; border-top: 1px solid #ccc" v-html="content"></div>
            <div style="height: 200px">
              <textarea v-model="text" style="height: 100px; width: 90%; padding: 20px; border: none; border-top: 1px solid #ccc;
               border-bottom: 1px solid #ccc; outline: none;resize: none"></textarea>
              <div style="text-align: right; padding-right: 30px">
                <el-button type="primary" size="default" @click="send">发送</el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
</template>

<script>
import { User,Search,Lock,DArrowLeft } from "@element-plus/icons-vue";
import $ from 'jquery'
import axios from "axios";
import MainHeader from "@/components/common/MainHeader.vue";



let socket;
export default {
  name: "Message",
  components: { MainHeader },
  data() {
    return {
      circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      user: {},
      isCollapse: false,
      users: [],
      chatUser: {},
      text: "",
      messages: [],
      content: '',
      user_id:0,
      username:"",
      keyword:"",
      searchUsers: []
    }
  },
  created() {
    this.init()
  },
  methods: {
    send() {
      if (!this.chatUser) {
        this.$message({type: 'warning', message: "请选择私信对象",duration:2000})
        return;
      }
      if (!this.text) {
        this.$message({type: 'warning', message: "请输入内容",duration:2000})
      } else {
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          let message = {
            src_id: this.user.id,
            target_id: this.chatUser.id,
            type: 0,
            content:this.text}

          this.$axios
              .post(`${this.$target}/message/one`,JSON.stringify(message),{
                headers: {
                  'Content-Type': 'application/json;charset=utf-8'
                }
              })
              .then(res=>{
                if(res.data.status==0){
                  this.$message({type: 'success', message: "发送成功",duration:1000})
                  this.messages.push({user: this.user.username, text: this.text})
                }else{
                  this.$message({type: 'error', message: "发送失败",duration:2000})
                }
              })

          // socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
          // this.messages.push({user: this.user.username, text: this.text})

          // 构建消息内容，本人消息
          this.createContent(null, this.user.username, this.text)
          this.text = '';
        }
      }
    },
    change(chatUser,mode) {
      //选中当前聊天对象
      this.chatUser = chatUser
      //清空聊天框
      this.content = ''

      //判断选中的聊天对象来自搜索结果还是最近联系
      if(mode === 0){
        //来自搜索结果，则判断是否有聊天关系，无则添加
        this.$axios
            .get(`${this.$target}/message/chatted?src_id=`+this.user.id+`&target_id=`+this.chatUser.id)
            .then(res=>{
              if(!res.data.data){
                this.$axios
                    .post(`${this.$target}/message/add?src_id=`+this.user.id+`&target_id=`+this.chatUser.id)
                    .then(res=>{
                      if(res.data.data){
                        this.$message({type: 'success', message: "发起聊天",duration:2000})
                        // this.users.push(chatUser)
                      }
                      else this.$message({type: 'error', message: "发起聊天失败",duration:2000})
                    })
              }
            })
      }


      //获取与选中用户的聊天记录
      this.$axios
          .get(`${this.$target}/message/records?src_id=`+this.user.id+`&target_id=`+this.chatUser.id)
          .then(res=>{
            if(res.data.status==0){
              let records = res.data.data
              for(let i=0;i<records.length;i++){
                if(records[i].src_id === this.user.id){
                  //该消息由当前用户发出
                  this.createContent(null, this.user.username, records[i].content)
                }else {
                  //该消息由当前用户接收
                  this.createContent(records[i].src_id, null, records[i].content)
                }
              }

            }
          })


    },
    createContent(remoteUser, nowUser, text) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
      let html
      // 当前用户消息
      if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
            "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
            "    <div class=\"tip left\">" + text + "</div>\n" +
            "  </div>\n" +
            "  <div class=\"el-col el-col-2\">\n" +
            "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
            "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
            "  </span>\n" +
            "  </div>\n" +
            "</div>";
      } else if (remoteUser) {   // remoteUser表示远程用户聊天消息，蓝色的气泡
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
            "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
            "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
            "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
            "  </span>\n" +
            "  </div>\n" +
            "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px\">\n" +
            "    <div class=\"tip right\">" + text + "</div>\n" +
            "  </div>\n" +
            "</div>";
      }
      console.log(html)
      this.content += html;
    },
    init() {
      // console.log(JSON.parse(localStorage.getItem("user")).id)
      this.user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
      this.username = this.user.username;
       this.user_id = this.user.id;
      let _this = this;
      this.$axios
          .get(`${this.$target}/message/users?user_id=`+this.user_id)
          .then(res=>{
            if(res.data.status==0){
              this.users = res.data.data
              // console.log(this.users[0].username)
              // this.users = JSON.parse(res.data.data)
            }
          })


      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:8080/websocket/" + this.user_id;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data)
          let data = JSON.parse(msg.data)  // 对收到的json数据进行解析

          if (data.src_id === _this.chatUser.id){
            //接收来自当前选中的聊天对象的消息，将消息内容及时添加到聊天框中
            _this.messages.push(data)
            // 构建消息内容
            _this.createContent(data.src_id, null, data.content)
          }

        };

        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        }
      }
    },
    searchUser() {
      if(this.keyword === ""){
        this.searchUsers = []
      }else {
        this.$axios
          .get(`${this.$target}/user/keyword?keyword=`+this.keyword+`&user_id=`+this.user.id)
          .then(res=>{
            if(res.data.status==0){
              this.searchUsers = res.data.data

            }
          })
      }

    }
  }
}
</script>



<style>
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width:auto;
  display:inline-block !important;
  display:inline;
}
.right {
  background-color: deepskyblue;
}
.left {
  background-color: forestgreen;
}
</style>
